﻿
using System.Web;
using Foothill.Common.Logging;
using System;
using System.Collections.Generic;

namespace Foothill.Service.Session
{
    using Exceptions;
    
    public class SessionService : ISessionService
    {
        public void AddSessionValue(string sessionName, object value)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                Log.Error(FoothillModule.Service, "HttpContext or Session is not available");
                return;
            }

            HttpContext.Current.Session[sessionName] = value;
        }

        public void SaveSessionValue(string sessionName, object value)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                Log.Error(FoothillModule.Service, "HttpContext or Session is not available");
                return;
            }

            HttpContext.Current.Session[sessionName] = value;
        }

        public void ClearSessionVariable(string sessionName)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                Log.Error(FoothillModule.Service, "HttpContext or Session is not available");
                return;
            }

            HttpContext.Current.Session[sessionName] = null;
        }

        // get session value, return null if key is not found 
        public object GetSessionValue(string key)
        {
            if ( HttpContext.Current == null || HttpContext.Current.Session == null )
            {
                Log.Error(FoothillModule.Service, "HttpContext or Session is not available");
                return null;
            }

            try
            {
                return HttpContext.Current.Session[key];
            }
            catch (Exception exception)
            {
                Log.Error(FoothillModule.Service, string.Format("Failed to get value for session named {0}", key), exception);
                return null;
            }
        }

        public UserContext GetUserContext()
        {
            UserContext retVal = GetSessionValue(SessionNames.UserContext) as UserContext;

            if (retVal == null)
            {
                // if currently no UserContext in the session, create a new one, this ensures there is always a UserContext
                retVal = new UserContext();
                SaveUserContext(retVal);
            }

            return retVal;
        }
      
        public void SaveUserContext(UserContext userContext)
        {
            SaveSessionValue(SessionNames.UserContext, userContext);
        }
    }
}
